module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.goods = this.model("taoke/goods");
		this.order = this.model("taoke/order");
		this.wxuser = this.model("weixin/user");
		this.queue = this.model("taoke/queue");
		this.conf = this.model("weixin/config");
		this.asset = this.model("system/asset");
		this.message = this.model("system/message");
		this.setup = this.model("system/setup");
		this.appid = think.config('setup.weixinAppid');
	}
	__before() {
		//		if(!this.isCli) {
		//			return this.fail("只支持命令行运行！");
		//		}
	}
	async fetchGoodsAction() {
		const setup = think.config("setup");
		let url = setup.goodsUrl;
		let sql = `CREATE TABLE IF NOT EXISTS tbk_goods_temp (
					  id int(10) NOT NULL AUTO_INCREMENT,
					  d_title varchar(50) DEFAULT NULL COMMENT '商品简称',
					  title varchar(255) DEFAULT NULL COMMENT '商品名称',
					  score decimal(2,1) DEFAULT NULL COMMENT '商品评分',
					  commission_queqiao decimal(10,2) DEFAULT NULL COMMENT '高佣鹊桥佣金比例',
					  quan_receive int(10) DEFAULT NULL COMMENT '已领券数量',
					  quan_price decimal(10,2) DEFAULT NULL COMMENT '优惠券金额',
					  yongjin_type tinyint(2) DEFAULT NULL COMMENT '佣金类型',
					  quan_time varchar(255) DEFAULT NULL COMMENT '优惠券结束时间',
					  jihua_link varchar(255) DEFAULT NULL COMMENT '计划链接',
					  price decimal(10,2) DEFAULT NULL COMMENT '券后价',
					  jihua_shenhe tinyint(1) DEFAULT NULL COMMENT '计划审核状态',
					  introduce varchar(255) DEFAULT NULL COMMENT '商品文案',
					  cid smallint(6) DEFAULT NULL COMMENT '分类ID',
					  sales_num int(10) DEFAULT NULL COMMENT '商品销量',
					  quan_link varchar(255) DEFAULT NULL COMMENT '手机券链接',
					  istmall tinyint(2) NOT NULL COMMENT '是否天猫',
					  goods_id bigint(16) NOT NULL COMMENT '商品淘宝id',
					  commission_jihua decimal(10,2) DEFAULT NULL COMMENT '计划(通用)佣金比例',
					  otth_id int(10) DEFAULT NULL COMMENT '大淘客ID',
					  que_siteid int(10) DEFAULT NULL COMMENT '鹊桥网站ID',
					  commission decimal(10,2) DEFAULT NULL COMMENT '佣金比例',
					  pic varchar(255) DEFAULT NULL COMMENT '商品主图 ',
					  org_price decimal(10,2) DEFAULT NULL COMMENT '正常售价',
					  quan_m_link varchar(255) DEFAULT NULL COMMENT '手机券短链',
					  quan_id varchar(255) DEFAULT NULL COMMENT '优惠券ID',
					  quan_condition varchar(255) DEFAULT NULL COMMENT '优惠券使用条件',
					  quan_surplus int(10) DEFAULT NULL COMMENT '优惠券剩余数量',
					  seller_id bigint(16) DEFAULT NULL COMMENT '卖家ID',
					  PRIMARY KEY (id),
					  KEY goods_id (goods_id)
					) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;`
		await this.goods.execute(sql);
		await this.goods.save(url);
	}
	//定时更新订单
	async updateOrderAction() {
		const alimama = think.service("alimama");
		let orders = await alimama.getOrders();
		if(!think.isEmpty(orders)) {
			await this.order.updateOrder(orders);
		}
		await think.timeout(1000);
		orders = await alimama.getOrders("settle_time");
		if(!think.isEmpty(orders)) {
			await this.order.updateOrder(orders);
		}
	}
	//定时绑定列队订单
	async bindOrderAction() {
		let self = this;
		let queue = await this.queue.select();
		if(!think.isEmpty(queue)) {
			for(let v of queue) {
				let order = await this.order.where({
					order_sn: v.order_sn
				}).select();
				if(!think.isEmpty(order)) {
					if(think.isEmpty(order[0].user_id)) {
						let asset = await self.asset.db(self.order.db()).where({
							user_id: v.user_id
						}).find();
						for(let o of order) {
							await self.order.bindOrder(o, asset);
						}
					}
					await self.queue.db(self.order.db()).where({
						id: v.id
					}).delete();
				}
			}
		}
	}
	async updateQueueAction() {
		let time = new Date().valueOf() - 1200000;
		let wait = await this.queue.where({
			create_time: ['<', time]
		}).select();
		let self = this;
		console.log(wait);
		for(const v of wait) {
			await this.queue.transaction(async() => {
				await self.message.db(self.queue.db()).add({
					type: 8,
					create_time: new Date().valueOf(),
					user_id: v.user_id,
					content: `订单编号【${v.order_sn}】绑定失败,订单未找到`
				});
				return await this.queue.where({
					id: v.id
				}).delete();
			});
		}
	}
	async messagePushAction() {
		let time = new Date().valueOf() - 24 * 3600 * 1000;
		let messages = await this.message.where({
			is_notified: 0,
			create_time: ['>', time]
		}).select();
		const weixin = await this.conf.where({
			appid: this.appid
		}).find();
		if(think.isEmpty(weixin)){
			return this.fail("请先再微信模块配置公众号")
		}
		let api = await this.wechatApi(weixin.id);
		messages.forEach(async(message) => {
			let openid = await this.wxuser.where({
				user_id: message.user_id
			}).getField("openid", true);
			try {
				if(!think.isEmpty(openid)) {
					await api.sendText(openid, message.content);
				}
			} catch(e) {
				await this.message.where({
					id: message.id
				}).update({
					is_notified: 2,
				});
			}
			await this.message.where({
				id: message.id
			}).update({
				is_notified: 1,
			});
		});
	}
	async refreshSessionAction() {
		const alimama = think.service("alimama");
		let data = await alimama.refreshSession();
		console.log(data);
		if(data.error) {
			const email = this.service("email");
			return await email.send({
				to: think.config("setup.adminEmail"),
				title: 'SESSION刷新出错',
				html: '高佣订单同步API授权SESSION刷新出错,请及时检查错误原因'
			});
		}
		if(data.re_expires_in <= 172800) {
			const email = this.service("email");
			await email.send({
				to: think.config("setup.adminEmail"),
				title: '授权到期提醒',
				html: '阿里妈妈高级API授权即将到期(2日内到期),请及时登录更新授权'
			});
		}
		await this.setup.where({
			code: 'taokeOrderSession'
		}).update({
			value: data.top_session
		});
		await this.setup.where({
			code: 'taokeOrderToken'
		}).update({
			value: data.refresh_token
		});
		const setup = await this.setup.selectAll();
		think.config('setup', setup);
		return this.success();
	}
}